package com.zhouxiaoxuan13.promotionservice.service;

import com.zhouxiaoxuan13.promotionservice.entity.FreshProduct;
import com.zhouxiaoxuan13.promotionservice.repository.FreshProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Service
public class FreshProductService {

    @Autowired
    private FreshProductRepository freshProductRepository;

    @Transactional(readOnly = true)
    public List<FreshProduct> getAllFreshProducts() {
        return freshProductRepository.findAll();
    }

    @Transactional(readOnly = true)
    public Optional<FreshProduct> getFreshProductById(Long id) {
        return freshProductRepository.findById(id);
    }

    @Transactional(readOnly = true)
    public Optional<FreshProduct> getFreshProductByName(String name) {
        return freshProductRepository.findByName(name);
    }

    @Transactional(readOnly = true)
    public List<FreshProduct> searchFreshProductsByName(String name) {
        return freshProductRepository.findByNameContainingIgnoreCase(name);
    }

    @Transactional(readOnly = true)
    public List<FreshProduct> getFreshProductsByCategory(String category) {
        return freshProductRepository.findByCategory(category);
    }

    @Transactional(readOnly = true)
    public List<FreshProduct> getPromotionProducts() {
        return freshProductRepository.findByIsOnPromotionTrue();
    }

    @Transactional
    public FreshProduct createFreshProduct(FreshProduct freshProduct) {
        // 设置默认值
        if (freshProduct.getIsOnPromotion() == null) {
            freshProduct.setIsOnPromotion(false);
        }
        if (freshProduct.getStockQuantity() == null) {
            freshProduct.setStockQuantity(0);
        }
        return freshProductRepository.save(freshProduct);
    }

    @Transactional
    public Optional<FreshProduct> updateFreshProduct(Long id, FreshProduct freshProductDetails) {
        return freshProductRepository.findById(id)
                .map(existingProduct -> {
                    existingProduct.setName(freshProductDetails.getName());
                    existingProduct.setDescription(freshProductDetails.getDescription());
                    existingProduct.setCategory(freshProductDetails.getCategory());
                    existingProduct.setSpecifications(freshProductDetails.getSpecifications());
                    existingProduct.setOriginalPrice(freshProductDetails.getOriginalPrice());
                    existingProduct.setStockQuantity(freshProductDetails.getStockQuantity());
                    existingProduct.setExpiryDate(freshProductDetails.getExpiryDate());
                    
                    // 如果不在促销中，清除促销相关信息
                    if (freshProductDetails.getIsOnPromotion() == null || !freshProductDetails.getIsOnPromotion()) {
                        existingProduct.setIsOnPromotion(false);
                        existingProduct.setPromotionPrice(null);
                        existingProduct.setPromotionId(null);
                    } else {
                        existingProduct.setIsOnPromotion(freshProductDetails.getIsOnPromotion());
                        existingProduct.setPromotionPrice(freshProductDetails.getPromotionPrice());
                        existingProduct.setPromotionId(freshProductDetails.getPromotionId());
                    }
                    
                    return freshProductRepository.save(existingProduct);
                });
    }

    @Transactional
    public boolean deleteFreshProduct(Long id) {
        if (freshProductRepository.existsById(id)) {
            freshProductRepository.deleteById(id);
            return true;
        }
        return false;
    }

    // 更新商品的促销信息（由促销服务调用）
    @Transactional
    public int updatePromotionInfo(String productName, BigDecimal promotionPrice, Boolean isOnPromotion, Long promotionId) {
        return freshProductRepository.updatePromotionInfoByName(productName, promotionPrice, isOnPromotion, promotionId);
    }

    // 清除指定促销的所有商品促销信息
    @Transactional
    public int clearPromotionInfo(Long promotionId) {
        return freshProductRepository.clearPromotionInfoByPromotionId(promotionId);
    }

    // 根据关键词匹配查找商品（用于促销匹配）
    @Transactional(readOnly = true)
    public List<FreshProduct> findMatchingProducts(String keyword) {
        return freshProductRepository.findByNameMatching(keyword);
    }

    // 检查库存预警
    @Transactional(readOnly = true)
    public List<FreshProduct> getLowStockProducts(Integer threshold) {
        return freshProductRepository.findByStockQuantityLessThan(threshold != null ? threshold : 10);
    }
}
